import React, { useState, useEffect, useCallback } from "react";
import { TensionSectionAPI } from "@/api/tensionSection";
import { ProjectAPI } from "@/api/project";
import { TowerAPI } from "@/api/Towers";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ConstructionMethodTemplateAPI } from "@/api/ConstructionMethodTemplate";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { RecommendAPI } from "@/api/Recommends";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Plus,
  Search,
  Trash2,
  Edit,
  RefreshCw,
  AlertTriangle,
  GitBranch,
  MoreHorizontal,
  FileText,
  Sparkles,
  Info,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import TensionSectionForm from "../components/tension-sections/TensionSectionForm.jsx";
import TensionSectionSchemeCreator from "../components/tension-sections/TensionSectionSchemeCreator";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";

export default function TensionSections() {
  const [tensionSections, setTensionSections] = useState([]);
  const [projects, setProjects] = useState([]);
  const [towers, setTowers] = useState([]);
  const [crossingPoints, setCrossingPoints] = useState([]);
  const [methodTemplates, setMethodTemplates] = useState([]);
  const [schemes, setSchemes] = useState([]);
  const [filteredSections, setFilteredSections] = useState([]);
  const [selectedProjectId, setSelectedProjectId] = useState("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [showForm, setShowForm] = useState(false);
  const [editingSection, setEditingSection] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showSchemeCreator, setShowSchemeCreator] = useState(false);
  const [schemeCreationMode, setSchemeCreationMode] = useState("manual");
  const [sectionsForScheme, setSectionsForScheme] = useState([]);
  const [isAiRecommending, setIsAiRecommending] = useState(false);
  const [aiRecommendData, setAiRecommendData] = useState(null);
  const [deletingSectionId, setDeletingSectionId] = useState(null); // 新增：跟踪正在删除的勘查单ID
  const { toast } = useToast();
  const navigate = useNavigate();

  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [paginatedSections, setPaginatedSections] = useState([]);

  const loadData = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const [
        sectionsData,
        projectsData,
        towersData,
        crossingPointsData,
        templatesData,
        schemesData,
      ] = await Promise.all([
        TensionSectionAPI.getList(),
        ProjectAPI.getList(),
        TowerAPI.getList(),
        CrossingPointAPI.getList(),
        ConstructionMethodTemplateAPI.getList(),
        ConstructionSchemeAPI.getList(),
      ]);
      setTensionSections(
        Array.isArray(sectionsData.data) ? sectionsData.data : []
      );
      setProjects(Array.isArray(projectsData.data) ? projectsData.data : []);
      setTowers(Array.isArray(towersData.data) ? towersData.data : []);
      setCrossingPoints(
        Array.isArray(crossingPointsData.data) ? crossingPointsData.data : []
      );
      setMethodTemplates(
        Array.isArray(templatesData.data) ? templatesData.data : []
      );
      setSchemes(Array.isArray(schemesData.data) ? schemesData.data : []);
    } catch (error) {
      console.error("加载数据失败:", error);
      setError("加载数据失败，请重试");
      toast({
        variant: "destructive",
        title: "加载失败",
        description: error.message,
      });
    } finally {
      setIsLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  useEffect(() => {
    let currentFiltered = tensionSections;

    if (selectedProjectId !== "all") {
      currentFiltered = currentFiltered.filter(
        (s) => s.projectId === selectedProjectId
      );
    }

    if (searchTerm) {
      currentFiltered = currentFiltered.filter(
        (s) =>
          s.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          s.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    setFilteredSections(currentFiltered);
    // 重置分页到第一页
    setCurrentPage(1);
  }, [tensionSections, selectedProjectId, searchTerm]);

  // 处理分页逻辑
  useEffect(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    setPaginatedSections(filteredSections.slice(startIndex, endIndex));
  }, [filteredSections, currentPage, itemsPerPage]);

  // 分页控制函数
  const handlePageChange = (pageNum) => {
    const totalPages = Math.ceil(filteredSections.length / itemsPerPage);
    if (pageNum < 1 || pageNum > totalPages) return;
    setCurrentPage(pageNum);
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 重置到第一页
  };

  // 渲染分页组件
  const renderPagination = () => {
    if (isLoading) return null;

    const totalItems = filteredSections.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-6 py-4 border-t border-gray-200 bg-white">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示
          {(currentPage - 1) * itemsPerPage + 1} 到
          {Math.min(currentPage * itemsPerPage, totalItems)} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8">
                每页 {itemsPerPage} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={count}
                  onClick={() => handleItemsPerPageChange(count)}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              <span className="sr-only">上一页</span>
            </Button>

            {totalPages > 0 &&
              Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="icon"
                    className="h-8 w-8"
                    onClick={() => handlePageChange(pageNum)}
                  >
                    {pageNum}
                  </Button>
                );
              })}

            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages || totalPages === 0}
            >
              <ChevronRight className="h-4 w-4" />
              <span className="sr-only">下一页</span>
            </Button>
          </div>
        </div>
      </div>
    );
  };

  const handleSubmit = async (sectionData) => {
    try {
      if (editingSection) {
        await TensionSectionAPI.update(editingSection.id, sectionData);
        toast({ title: "更新成功", description: "勘查单信息已更新" });
      } else {
        await TensionSectionAPI.create(sectionData);
        toast({ title: "创建成功", description: "勘查单已创建" });
      }
      setShowForm(false);
      setEditingSection(null);
      loadData();
    } catch (error) {
      console.error("保存勘查单失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message,
      });
    }
  };

  const handleEdit = (section) => {
    setEditingSection(section);
    setShowForm(true);
  };

  // 优化：删除勘查单时同时删除关联方案
  const handleDelete = async (section) => {
  
    // 增强确认提示，告知会删除关联方案
    if (
      !window.confirm(
        `确定要删除勘查单"${section.name}"吗？此操作将同时删除所有关联的施工方案，且无法撤销。`
      )
    ) {
      return;
    }
    try {
      setDeletingSectionId(section.id); // 设置删除中状态
      await TensionSectionAPI.delete(section.id);
      toast({ title: "删除成功", description: "勘查单已删除" });

      // 4. 重新加载数据
      loadData();
    } catch (error) {
      console.error("删除勘查单及关联方案失败:", error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: `删除过程中出现错误：${error.message}`,
      });
    } finally {
      setDeletingSectionId(null); // 重置删除中状态
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingSection(null);
  };

  // 单个创建方案（支持手动和智能模式）
  const handleCreateScheme = async (section, mode) => {
    setSectionsForScheme([section]);
    setSchemeCreationMode(mode);

    // 智能模式下调用AI推荐接口
    if (mode === "smart") {
      setIsAiRecommending(true);
      try {
        const recommendResult = await RecommendAPI.aiRecommend(section.id);
        console.log("AI推荐结果:", recommendResult.data);
        setAiRecommendData(recommendResult.data);
        setShowSchemeCreator(true);
      } catch (error) {
        console.error("AI推荐失败:", error);
        toast({
          variant: "destructive",
          title: "智能推荐失败",
          description: error.message || "获取AI推荐方案时出现错误，请重试",
        });
        setIsAiRecommending(false);
      }
    } else {
      // 手动模式直接打开创建器
      setAiRecommendData(null);
      setShowSchemeCreator(true);
    }
  };

  const handleSchemeCreated = () => {
    console.log("方案创建成功回调");
    setShowSchemeCreator(false);
    setSectionsForScheme([]);
    setAiRecommendData(null);
    toast({
      title: "方案创建成功",
      description: "施工方案已成功创建",
    });
    loadData();
  };

  const handleSchemeCreatorCancel = () => {
    console.log("取消创建方案");
    setShowSchemeCreator(false);
    setSectionsForScheme([]);
    setAiRecommendData(null);
    setIsAiRecommending(false); // 确保取消时重置加载状态
  };

  const getProjectName = (projectId) => {
    const project = projects.find((p) => p.id === projectId);
    return project ? project.projectName : "未知项目";
  };

  const getTowerNumber = (towerId) => {
    const tower = towers.find((t) => t.id === towerId);
    return tower ? tower.towerNumber : "未知";
  };

  const handleClearFilters = () => {
    setSelectedProjectId("all");
    setSearchTerm("");
    toast({
      title: "筛选条件已清除",
      description: "已显示所有勘查单",
    });
  };

  const isFilteringActive = selectedProjectId !== "all" || searchTerm;
  const activeFilters = [];
  if (selectedProjectId !== "all") {
    activeFilters.push(`项目: ${getProjectName(selectedProjectId)}`);
  }
  if (searchTerm) {
    activeFilters.push(`搜索: "${searchTerm}"`);
  }

  const getLatestSchemeForSection = (sectionId) => {
    const sectionSchemes = schemes.filter(
      (s) => s.tensionSectionId === sectionId
    );
    if (sectionSchemes.length === 0) return null;
    return sectionSchemes.sort(
      (a, b) =>
        new Date(b.createdDate).getTime() - new Date(a.createdDate).getTime()
    )[0];
  };

  const handleViewScheme = (scheme) => {
    if (scheme && scheme.id) {
      navigate(createPageUrl(`SchemeAnalysis?id=${scheme.id}`));
    }
  };

  return (
    <div className="p-4 md:p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-screen-2xl mx-auto">
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              勘察单管理
            </h1>
            <p className="text-gray-600">管理项目中的所有勘查单信息</p>
          </div>
          <div className="flex gap-3 flex-wrap">
            <Button
              onClick={() => setShowForm(true)}
              className="bg-blue-600 hover:bg-blue-700"
              disabled={isAiRecommending}
            >
              <Plus className="w-4 h-4 mr-2" />
              新建勘查单
            </Button>
          </div>
        </div>

        {error && (
          <Alert variant="destructive ">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription className="flex items-center justify-between">
              <span>{error}</span>
              <Button variant="outline" size="sm" onClick={loadData}>
                <RefreshCw className="w-4 h-4 mr-1" />
                重试
              </Button>
            </AlertDescription>
          </Alert>
        )}

        <Card className="mb-6">
          <CardContent className="p-4 space-y-3 ">
            {selectedProjectId === "all" && filteredSections.length > 20 && (
              <Alert className="bg-blue-50 border-blue-200">
                <Info className="h-4 w-4 text-blue-600" />
                <AlertDescription className="text-blue-800">
                  <span className="font-medium">提示：</span>
                  当前显示所有项目的勘查单数据。建议选择具体项目进行查看，以便更好地管理和浏览。
                </AlertDescription>
              </Alert>
            )}
            <div className="flex flex-col md:flex-row gap-4 items-center ">
              <div className="relative flex-1 w-full md:w-auto">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="搜索勘查单名称..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              <Select
                value={selectedProjectId}
                onValueChange={setSelectedProjectId}
              >
                <SelectTrigger className="w-full md:w-48">
                  <SelectValue placeholder="选择项目" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部项目</SelectItem>
                  {projects.map((p) => (
                    <SelectItem key={p.id} value={p.id}>
                      {p.projectName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {isFilteringActive && (
          <Alert className="mb-6 bg-blue-50 border-blue-200 text-blue-800">
            <Info className="h-4 w-4" />
            <AlertDescription className="flex items-center justify-between flex-wrap">
              <span className="flex items-center flex-wrap">
                筛选条件已应用：
                {activeFilters.map((filter, index) => (
                  <Badge
                    key={index}
                    variant="secondary"
                    className="ml-2 mt-1 mb-1 bg-blue-100 text-blue-800"
                  >
                    {filter}
                  </Badge>
                ))}
              </span>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleClearFilters}
                className="text-blue-700 hover:bg-blue-100 mt-2 sm:mt-0"
              >
                <RefreshCw className="w-4 h-4 mr-1" />
                清除筛选
              </Button>
            </AlertDescription>
          </Alert>
        )}
{/* 
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
          <Card className="bg-gradient-to-r from-purple-50 to-purple-100 border-purple-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-purple-600">
                    总勘查单
                  </p>
                  <p className="text-2xl font-bold text-purple-700">
                    {filteredSections.length}
                  </p>
                </div>
                <GitBranch className="w-8 h-8 text-purple-500" />
              </div>
            </CardContent>
          </Card>
          <Card className="bg-gradient-to-r from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600">平均长度</p>
                  <p className="text-2xl font-bold text-blue-700">
                    {filteredSections.length > 0
                      ? (
                          filteredSections.reduce(
                            (sum, s) => sum + (s.totalLength || 0),
                            0
                          ) / filteredSections.length
                        ).toFixed(1)
                      : 0}{" "}
                    m
                  </p>
                </div>
                <Badge className="bg-blue-500" />
              </div>
            </CardContent>
          </Card>
        </div> */}

        {showForm && (
          <TensionSectionForm
            tensionSection={editingSection}
            projects={projects}
            towers={towers}
            crossingPoints={crossingPoints}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
          />
        )}

        {showSchemeCreator && (
          <TensionSectionSchemeCreator
            tensionSections={sectionsForScheme}
            projects={projects}
            towers={towers}
            crossingPoints={crossingPoints}
            methodTemplates={methodTemplates}
            mode={schemeCreationMode}
            aiRecommendData={aiRecommendData}
            onSuccess={handleSchemeCreated}
            onCancel={handleSchemeCreatorCancel}
          />
        )}

        <Card>
          <CardHeader>
            <CardTitle>勘查单列表 ({filteredSections.length})</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="text-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
                <p className="text-gray-500">加载中...</p>
              </div>
            ) : filteredSections.length === 0 ? (
              <div className="text-center py-12">
                <GitBranch className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无勘查单
                </h3>
                <p className="text-gray-500 mb-6">创建您的第一个勘查单</p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  新建勘查单
                </Button>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <Table className="w-full border-collapse rounded-lg overflow-hidden">
                    <TableHeader className="bg-gray-50 border-b border-gray-200">
                      <TableRow>
                        <TableHead className="min-w-[280px] py-3 px-4 font-semibold text-gray-700">
                          勘查单名称
                        </TableHead>
                        <TableHead className="min-w-[220px] py-3 px-4 font-semibold text-gray-700">
                          所属项目
                        </TableHead>
                        <TableHead className="w-24 py-3 px-4 font-semibold text-gray-700 text-center">
                          起始塔
                        </TableHead>
                        <TableHead className="w-24 py-3 px-4 font-semibold text-gray-700 text-center">
                          结束塔
                        </TableHead>
                        <TableHead className="w-20 py-3 px-4 font-semibold text-gray-700 text-center">
                          塔数
                        </TableHead>
                        <TableHead className="w-24 py-3 px-4 font-semibold text-gray-700 text-right">
                          总长度(m)
                        </TableHead>
                        <TableHead className="w-24 py-3 px-4 font-semibold text-gray-700 text-right">
                          代表档距(m)
                        </TableHead>
                        <TableHead className="w-20 py-3 px-4 font-semibold text-gray-700 text-center">
                          跨越点数
                        </TableHead>
                        <TableHead className="min-w-[200px] py-3 px-4 font-semibold text-gray-700">
                          关联方案
                        </TableHead>
                        <TableHead className="w-12 py-3 px-4 font-semibold text-gray-700 text-right">
                          操作
                        </TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {paginatedSections.map((section, index) => {
                        const latestScheme = getLatestSchemeForSection(
                          section.id
                        );
                        // 优化斑马条纹对比度
                        const rowBg = 
                          index % 2 === 0 ? "bg-white" : "bg-gray-50";
                        const isDeleting = deletingSectionId === section.id; // 判断是否正在删除

                        return (
                          <TableRow
                            key={section.id}
                            className={`${rowBg} hover:bg-blue-50/50 transition-colors duration-150 border-t border-gray-100 ${
                              isDeleting ? "opacity-50" : ""
                            }`}
                          >
                            <TableCell
                              className="py-3 px-4 align-middle font-medium text-gray-900 cursor-pointer"
                              onClick={() => handleEdit(section)}
                            >
                              <div className="truncate max-w-[280px]">
                                {section.name}
                              </div>
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle text-gray-600">
                              <div className="truncate max-w-[220px]">
                                {getProjectName(section.projectId)}
                              </div>
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle font-mono text-gray-700 text-center">
                              {getTowerNumber(section.startTensionTowerId) ||
                                "-"}
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle font-mono text-gray-700 text-center">
                              {getTowerNumber(section.endTensionTowerId) || "-"}
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle text-center">
                              <Badge
                                variant="outline"
                                className="bg-gray-100 px-2.5 py-0.5"
                              >
                                {section.intermediateTowerIds
                                  ? section.intermediateTowerIds.length + 2
                                  : 0}
                              </Badge>
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle font-medium text-gray-800 text-right">
                              {section.totalLength
                                ? section.totalLength.toFixed(1)
                                : "-"}
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle font-medium text-emerald-600 text-right">
                              {section.calculatedRulingSpan
                                ? section.calculatedRulingSpan.toFixed(1)
                                : "-"}
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle text-center">
                              <Badge
                                className={
                                  section.associatedCrossingPointIds?.length > 0
                                    ? "bg-blue-100 text-blue-800 hover:bg-blue-200 px-2.5 py-0.5"
                                    : "bg-gray-100 text-gray-600 px-2.5 py-0.5"
                                }
                              >
                                {section.associatedCrossingPointIds
                                  ? section.associatedCrossingPointIds.length
                                  : 0}
                              </Badge>
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle text-left">
                              {latestScheme ? (
                                <Button
                                  variant="link"
                                  onClick={() => handleViewScheme(latestScheme)}
                                  className="p-0 h-auto text-blue-600 hover:text-blue-800 hover:underline truncate min-w-[0] max-w-[250px] inline-block text-left"
                                >
                                  {latestScheme.name}
                                </Button>
                              ) : (
                                <span className="text-sm italic text-gray-500">
                                  无方案
                                </span>
                              )}
                            </TableCell>
                            <TableCell className="py-3 px-4 align-middle text-right">
                              <div className="flex items-center justify-end gap-1">
                                <DropdownMenu>
                                  <DropdownMenuTrigger asChild>
                                    <Button
                                      variant="ghost"
                                      size="icon"
                                      className="h-8 w-8 rounded-full hover:bg-gray-200 transition-colors"
                                      disabled={isAiRecommending || isDeleting} // 删除时禁用操作按钮
                                    >
                                      <MoreHorizontal className="w-4 h-4 text-gray-600" />
                                    </Button>
                                  </DropdownMenuTrigger>
                                  <DropdownMenuContent
                                    align="end"
                                    className="w-48"
                                  >
                                    <DropdownMenuItem
                                      onClick={() => handleEdit(section)}
                                      className="cursor-pointer"
                                      disabled={isDeleting}
                                    >
                                      <Edit className="w-4 h-4 mr-2" />
                                      编辑
                                    </DropdownMenuItem>

                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem
                                      onClick={() =>
                                        handleCreateScheme(section, "manual")
                                      }
                                      className="cursor-pointer"
                                      disabled={isAiRecommending || isDeleting}
                                    >
                                      <FileText className="w-4 h-4 mr-2" />
                                      手动创建方案
                                    </DropdownMenuItem>

                                    <DropdownMenuItem
                                      onClick={() =>
                                        handleCreateScheme(section, "smart")
                                      }
                                      className="cursor-pointer"
                                      disabled={isAiRecommending || isDeleting}
                                    >
                                      {isAiRecommending ? (
                                        <>
                                          <RefreshCw className="w-4 h-4 mr-2 animate-spin text-purple-600" />
                                          推荐中...
                                        </>
                                      ) : (
                                        <>
                                          <Sparkles className="w-4 h-4 mr-2 text-purple-600" />
                                          智能创建方案
                                        </>
                                      )}
                                    </DropdownMenuItem>

                                    <DropdownMenuSeparator />
                                    <DropdownMenuItem
                                      onClick={() => handleDelete(section)}
                                      className="text-red-600 cursor-pointer hover:bg-red-50"
                                      disabled={isDeleting}
                                    >
                                      {isDeleting ? (
                                        <>
                                          <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                                          删除中...
                                        </>
                                      ) : (
                                        <>
                                          <Trash2 className="w-4 h-4 mr-2" />
                                          删除
                                        </>
                                      )}
                                    </DropdownMenuItem>
                                  </DropdownMenuContent>
                                </DropdownMenu>
                              </div>
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </div>
                {/* 渲染分页组件 */}
                {renderPagination()}
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
